public class BinarySearchTree {
    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public TreeNode root = null;

    public boolean search(int val) { //二叉搜索树的查找
        TreeNode cur = root;
        while (cur != null) {
            if (cur.val < val) {
                cur = cur.right;
            } else if (cur.val > val) {
                cur = cur.left;
            } else {
                return true;
            }
        }
        return false;
    }

    public boolean insert(int val) {  //二叉搜索树的插入
        TreeNode node = new TreeNode(val);
        if (root == null) {
            root = node;
            return true;
        }
        TreeNode cur = root;
        TreeNode parent = null;
        while (cur != null) {
            if (val < cur.val) {
                parent = cur;
                cur = cur.left;
            } else if (val > cur.val) {
                parent = cur;
                cur = cur.right;
            } else {
                return false;
            }
        }
        if (parent.val < val) {
            parent.right = node;
        } else {
            parent.left = node;
        }
        return true;
    }


    public void remove(int val) {  //二叉搜索树的删除操作
        TreeNode cur = root;
        TreeNode parent = null;
        while (cur != null) {
            if (val < cur.val) {
                parent = cur;
                cur = cur.left;
            } else if (val > cur.val) {
                parent = cur;
                cur = cur.right;
            } else {
                removeNode(parent,cur);
                return;
            }
        }
    }
    public void removeNode(TreeNode parent,TreeNode cur){
        if (cur.left == null){  //当cur的左边为空
            if (cur == root){ // 且cur是root，那么证明整个树没有左树，此时要删除cur，就相当于删除根节点，即直接将根节点变为根节点的右孩子
                root = cur.right;
            } else if (cur == parent.left) { //cur不为root，删除cur，且cur的左树为空，此时直接将根节点的左孩子指向cur的右孩子即可
                parent.left = cur.right;
            }else {
                parent.right = cur.right;
            }
        } else if (cur.right == null) {//当cur的右边为空
            if (cur == root){
                root = cur.left;
            } else if (cur == parent.left) {
                parent.left = cur.left;
            }else {
                parent.right = cur.left;
            }
        }else { //当cur的左右都不为空
            TreeNode targetParent = cur;
            TreeNode target = cur.right;
            while (target != null){
                targetParent = target;
                target = target.left;
            }
            cur.val = target.val;
            if (target == targetParent.left){ //如果targetParent.left存在的话
                targetParent.left = target.right;
            }else {
                targetParent.right = target.right;
            }
        }



    }
}
